package com.hunantv.mglive.widget.Toast;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.hunantv.mglive.R;


/**
 * 转菊花的对话框
 * 
 * 默认情况下，点击返回按钮是不会退出对话框的，要设置该属性，可以采取下面两种方式
 * 1、通过设置重载构造函数的isDismissWhenBackPressed形参
 * 2、调用setIsDismissWhenBackPressed函数
 * 
 * @author fredliao
 */
public class ProgressDialog extends AlertDialog 
{
	private String mTip;
	private boolean mIsDismissWhenBackPressed = false;
	
	/**
	 * 转菊花对话框构造函数
	 * 
	 * @param context
	 *            ，上下文
	 * @param title
	 *            ，标题文案
	 */
	public ProgressDialog(Context context, String title)
	{
		super(context,R.style.dialog);
		this.mTip = title;
		
		// 需要设置setOwnerActivity，否则getOwnerActivity时候返回为空
	    if (context instanceof Activity) {
	        setOwnerActivity((Activity) context);
	    }
	}
	
	/**
	 * 转菊花对话框构造函数
	 * 
	 * @param context
	 *            ，上下文
	 * @param title
	 *            ，标题文案
	 * @param isDismissWhenBackPressed
	 *            ，点击返回按钮是否禁止         
	 */
	public ProgressDialog(Context context, String title, boolean isDismissWhenBackPressed)
	{
		this(context, title);
		this.mIsDismissWhenBackPressed = isDismissWhenBackPressed;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		initView();
		setCanceledOnTouchOutside(false);
	}
	
	private void initView()
	{
		setContentView(R.layout.common_layout_progressdialog);
		TextView tiptext=(TextView)findViewById(R.id.tipText);
		if(!TextUtils.isEmpty(mTip))
		{
			tiptext.setText(mTip);
			tiptext.setVisibility(View.VISIBLE);
		}else
		{
			tiptext.setVisibility(View.GONE);
		}

		ImageView tipImg = (ImageView) findViewById(R.id.tipImg);
		Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.progress_rotate);
		LinearInterpolator lin = new LinearInterpolator();
		animation.setInterpolator(lin);
		tipImg.startAnimation(animation);
	}
	
	/**
	 * 设置点击返回按钮是否退出
	 * 
	 * @param isDismissWhenBackPressed
	 *            ，设置点击返回按钮是否退出
	 */
	public void setIsDismissWhenBackPressed(boolean isDismissWhenBackPressed) 
	{
		this.mIsDismissWhenBackPressed = isDismissWhenBackPressed;
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event)
	{
		// 如果设置了物理返回键不消失的话，则屏蔽掉返回键
		if (!mIsDismissWhenBackPressed && keyCode == KeyEvent.KEYCODE_BACK) 
		{
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}
	
	/**
	 * 供外面调用的dismiss方法，调用该方法，可以不用进行activity是否存在，对话框是否显示的诸多判断
	 * 全部由方法内部实现
	 */
	public void dismiss()
	{
		//如果本身依附的activity还存在,则干掉对话框
		if(getOwnerActivity() != null && !getOwnerActivity().isFinishing() && this.isShowing()){
			super.dismiss();
		}
	}
}
